//
//  MainTabBarController.swift
//  艾小夕の微小博
//
//  Created by 艾小新 on 15/10/15.
//  Copyright © 2015年 艾小新. All rights reserved.
//

import UIKit

class MainTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        addChildViewController()

    }
    
    // 这个位置已经完全创建出了subViews视图，再添加懒加载的按钮，就默认在层次最上面了
    override func viewDidAppear(animated: Bool) {
        
        super.viewDidAppear(animated)
        
        setupComposebtn()
        
    }
    
    
    ///  一个TabBarController有四个NavGationController，每一个NavGationControllr的根视图是UITableViewController
    ///
    ///  - parameter childController: 增加TableViewController
    ///  - parameter title:           名称
    ///  - parameter imageName:       图片
    private func addChildViewController(childController: UIViewController,title :String,imageName :String) {
        
        let vc = childController
        
        vc.title = title 
        
        let nav = UINavigationController(rootViewController: vc)
        
        nav.tabBarItem.image = UIImage(named: imageName)
        
        addChildViewController(nav)
    }
    
    ///  增加四个Nav+Tbc
    private func addChildViewController() {
        
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        addChildViewController(UIViewController())
        addChildViewController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
    
    }
    
    
    ///  compose按钮单击事件
     func composeTouch() {
        
        print(__FUNCTION__)
    }
    
    
    private lazy var composebtn: UIButton = {
       
        let btn = UIButton(type: UIButtonType.Custom)
        
        btn.addTarget(self, action: "composeTouch", forControlEvents: UIControlEvents.TouchUpInside)
        
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        self.tabBar.addSubview(btn)
        
        return btn
        
    }()
    
    ///  设置按钮位置
    private func setupComposebtn() {
        
        let w = tabBar.bounds.width / CGFloat(viewControllers!.count)
        
        let rect = CGRect(x: 0, y: 0, width: w, height: tabBar.bounds.height)
        
        composebtn.frame = CGRectOffset(rect, 2 * w, 0)
        
    }
    

  
    
    
}
